<script setup lang="ts">
import type {
  IAddressPool,
  IAddressPoolGroup,
  IAddressPoolRule,
} from './types.ts'

import { v4 as uuidV4 } from 'uuid'
import AddressPoolGroup from './AddressPoolGroup.vue'

type ConfigureFn = (arr: IAddressPool[]) => IAddressPool[]
interface IEmit {
  (event: 'update:modelValue', value: IAddressPoolGroup[]): void
}

interface IProps {
  disabledAll?: boolean
  modelValue: IAddressPoolGroup[]
  // 匹配规则配置函数，会传入系统内置的所有规则配置，外部调用者可对系统配置进行覆盖重置
  configure?: ConfigureFn | ConfigureFn[]
}

const props = defineProps<IProps>()
const emit = defineEmits<IEmit>()
const groupRefs = ref<(typeof AddressPoolGroup)[]>([])
const addressPoolGroups = useVModel(props, 'modelValue', emit)
provide('groups', addressPoolGroups)
// 增强的自定义指令，通过参数控制
const vFocus = {
  mounted: (el: HTMLElement, binding: any) => {
    if (binding.value) {
      setTimeout(() => el.focus(), 10)
    }
  },
  updated: (el: HTMLElement, binding: any) => {
    if (binding.value !== binding.oldValue && binding.value) {
      setTimeout(() => el.focus(), 10)
    }
  },
}
/**
 * 组规则改变
 */
function handleGroupRuleChange(uuid: string, rules: IAddressPoolRule[]) {
  const group = addressPoolGroups.value.find(item => item.uuid === uuid)
  if (group) {
    group.address_pool_ids = rules
  }
}

/**
 * 新增组（或者）
 */
function handleAddGroup() {
  addressPoolGroups.value.push({
    uuid: uuidV4(),
    edit: false,
    name: `地址池集合${addressPoolGroups.value.length + 1}`,
    address_pool_ids: [{ uuid: uuidV4(), id: '' }],
  })
}

/**
 * 重置
 */
function reset() {
  addressPoolGroups.value = [
    {
      uuid: uuidV4(),
      name: '地址池集合1',
      edit: false,
      address_pool_ids: [{ uuid: uuidV4(), id: '' }],
    },
  ]
}
watch(
  () => addressPoolGroups.value.length,
  (newLength, oldLength) => {
    // 只有当从多组变为单组时才重置名称
    if (newLength === 1 && oldLength > 1) {
      addressPoolGroups.value[0].name = '地址池集合1'
    }
  },
)
// 验证数据
async function validate() {
  const res = await Promise.all(
    groupRefs.value.map(groupComp => groupComp.validate()),
  )
  return res
    .map((res: any) => res.every((item: any) => item === undefined))
    .every(item => item === true)
}
function moveAddressPoolGroup(index: number, direction: 'up' | 'down') {
  if (
    (direction === 'up' && index > 0)
    || (direction === 'down' && index < addressPoolGroups.value.length - 1)
  ) {
    const targetIndex = direction === 'up' ? index - 1 : index + 1
    // 交换位置
    ;[addressPoolGroups.value[index], addressPoolGroups.value[targetIndex]] = [
      addressPoolGroups.value[targetIndex],
      addressPoolGroups.value[index],
    ]
    return true // 移动成功
  }
  return false // 移动失败
}
defineExpose({
  reset,
  validate,
})
</script>

<template>
  <div class="address-pool-collection-view">
    <div
      v-for="(group, index) in addressPoolGroups"
      :key="group.uuid"
      class="address-pool-view"
    >
      <div class="address-pool-view__top">
        <div class="field flex-1">
          <div
            v-if="!group.edit"
            class="h-4 flex items-center gap-x-1"
          >
            {{ group.name }}
            <i-icons-edit
              class="edit-icon"
              @click="group.edit = true"
            />
          </div>
          <input
            v-else
            v-model="group.name"
            v-focus:active="group.edit"
            :maxLength="8"
            :minLength="1"
            class="h-4 leading-4 outline-none"
            @blur="
              () => {
                if (!group.name) {
                  group.name = `地址池集合${index + 1}`
                }
                group.edit = false
              }
            "
          >
        </div>
        <div class="field flex gap-x-2 text-center">
          <cloud-tooltip content="上移">
            <a-link
              class="custom-link"
              :disabled="addressPoolGroups.length === 1 || index === 0"
              @click="moveAddressPoolGroup(index, 'up')"
            >
              <template #icon>
                <i-icons-move-up />
              </template>
            </a-link>
          </cloud-tooltip>
          <cloud-tooltip content="下移">
            <a-link
              class="custom-link"
              :disabled="
                addressPoolGroups.length === 1
                  || index === addressPoolGroups.length - 1
              "
              @click="moveAddressPoolGroup(index, 'down')"
            >
              <template #icon>
                <i-icons-move-down />
              </template>
            </a-link>
          </cloud-tooltip>
          <cloud-tooltip content="删除">
            <a-link
              class="custom-link"
              status="danger"
              :disabled="addressPoolGroups.length === 1"
              @click="addressPoolGroups.splice(index, 1)"
            >
              <template #icon>
                <i-icons-move-close />
              </template>
            </a-link>
          </cloud-tooltip>
        </div>
      </div>
      <div class="address-pool-view__body">
        <address-pool-group
          ref="groupRefs"
          v-model:rules="group.address_pool_ids"
          :last="index === addressPoolGroups.length - 1"
          :disabled-all="disabledAll"
          @delete="addressPoolGroups.splice(index, 1)"
          @change="handleGroupRuleChange(group.uuid, $event)"
        />
      </div>
    </div>
    <div class="address-pool-collection">
      <a-button
        type="text"
        :disabled="addressPoolGroups.length >= 2"
        class="w-full"
        @click="handleAddGroup"
      >
        <i-icons-plus class="mr-1" />添加地址池集合
      </a-button>
    </div>
  </div>
</template>

<style lang="less">
@import './styles.less';
</style>
